﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ComponentModel.DataAnnotations;

namespace Cofe.Core.Validater
{
    /// <summary>
    /// Validate if PropertyPair's value is a valid filePath.
    /// </summary>
    public class FilePathAttribute : Attribute, IPropertyValidator 
    {
        public int MaxLength { get; set; }

        public FilePathAttribute(int maxLength = -1)
        {
            MaxLength = maxLength;
        }

        public ValidationResult GetValidationResult(object value)
        {
            if (value == null || !(value is string)) return new ValidationResult("Value is not a string");
                              
            string path = (value as string);

            if (path.IndexOf("..") != -1)
                return new ValidationResult("Illegal character(s) in filePath.");

            if (MaxLength != -1)
                if (path.Length > MaxLength)
                    return new ValidationResult(String.Format("Path length longer than {0}.", MaxLength));

            if (path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) != -1)
                return new ValidationResult("Illegal character(s) in filePath.");

            return ValidationResult.Success;
        }
    }
}
